package com.yxplearn.mybatisplus.util;

import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.yxplearn.mybatisplus.manager.PersistEntity;

import java.lang.reflect.Field;

public class JdbcUtil<T> {

    public static final JdbcUtil ins = new JdbcUtil();

    public void updateEntityPartParam(BaseMapper baseMapper, T t) throws IllegalAccessException {
        UpdateWrapper updateWrapper = new UpdateWrapper();
        Field parameterKey = null;
        for (Field field : t.getClass().getDeclaredFields()) {
            field.setAccessible(true);
            Object paramValue = field.get(t);
            if (field.getAnnotation(TableId.class) != null) {
                parameterKey = field;
                updateWrapper.eq(parameterKey.getName(), parameterKey.get(t));
                continue;
            }
            if (paramValue != null) {
                if (paramValue instanceof String) {
                    updateWrapper.set(field.getName(), (String) paramValue);
                }
            }
        }
        if (parameterKey == null) {
            throw new IllegalArgumentException("没有主键");
        }
        baseMapper.update(t, updateWrapper);
    }

    public void updateEntityPartParam(BaseMapper baseMapper, T t, String... params) throws IllegalAccessException, NoSuchFieldException {
        UpdateWrapper updateWrapper = new UpdateWrapper();
        for (String param : params) {
            Field field = t.getClass().getField(param);
            Object value = field.get(t);
            updateWrapper.set(param, updateWrapper.set(param, value));
        }
        baseMapper.update(t, updateWrapper);
    }
}
